//
//  CS_Page_MultitpleSelectView.m
//  Pods
//
//  Created by 浙大网新中研软件 on 2017/9/19.
//
//

#import "CS_Page_MultitpleSelectView.h"
#import "CSSelectableModel.h"

#define HEIGHT_CONDITION_BUTTON 35.0
#define MARGIN 10.0

@interface CSMainSelectView()

@property (nonatomic, strong) CSSelectableModel *model;

@property (strong, nonatomic) CS_Page_TextView *content_CS_Page_TextView;

@property (strong, nonatomic) CS_Page_SectionTitleView *content_CS_Page_SectionTitleView;

@property (nonatomic, strong) UIButton *clickButton;

@property (nonatomic, strong) UIFont *font;

@property (nonatomic, strong) UIColor *textColor;

@property (nonatomic, strong) UIColor *selectedColor;

@property (strong, nonatomic) UIImageView *checkImageView;

@end

@implementation CSMainSelectView

+(id)mainSelectView:(CSSelectableModel *)model textFont:(UIFont *)font textColor:(UIColor *)textColor selectedColor:(UIColor *)selectedColor{
    
    CSMainSelectView *mainSelectView = [CSMainSelectView new];
    mainSelectView.model = model;
    mainSelectView.font = font;
//    mainSelectView.selectedColor = selectedColor;
    mainSelectView.textColor = textColor;
    mainSelectView.selectedColor = selectedColor;
    return mainSelectView;
    
}

-(CGFloat)layoutView:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    UIImage *image = [CSPageEngine getImageWithKey:KEY_ICON_CHECKED];
    
    CGFloat localPrimarY = 13.0;
    CGFloat imageHeight = 13.0;
    CGFloat imageWidth = imageHeight;
    
    if (image) {
        imageHeight = 18.0;
        imageWidth = image.size.height / image.size.width * imageHeight;
    }
    
    if (self.isParentLevel) {
        
        localPrimarY = 0.0;
        
        self.content_CS_Page_SectionTitleView.rightMargin = CELL_EDIT_RIGHT_MARGIN + imageWidth + 10.0;
        
        localPrimarY = [self.content_CS_Page_SectionTitleView layoutView:self primaryY:localPrimarY];
        
        self.checkImageView.frame = CGRectMake(kWindowW - CELL_EDIT_RIGHT_MARGIN - imageWidth, 25.0, imageWidth, imageHeight);
        
        if (![self isNullOrEmpty:self.model.color]) {
            UIView *colorBarView = [[UIView alloc] init];
            colorBarView.backgroundColor = [UIColor colorFromHexCode:self.model.color];
            colorBarView.frame = CGRectMake(kWindowW - CELL_EDIT_RIGHT_MARGIN - imageWidth - 100 - CELL_EDIT_RIGHT_MARGIN, 25.0, 100, imageHeight);
            [self addSubview:colorBarView];
        }
        
    }else{
        
        self.content_CS_Page_TextView.rightMargin = CELL_EDIT_RIGHT_MARGIN + imageWidth + 10.0;
        
        localPrimarY = [self.content_CS_Page_TextView layoutView:self primaryY:localPrimarY];
        
        self.checkImageView.frame = CGRectMake(kWindowW - CELL_EDIT_RIGHT_MARGIN - imageWidth, 15.0, imageWidth, imageHeight);
        
        if (![self isNullOrEmpty:self.model.color]) {
            UIView *colorBarView = [[UIView alloc] init];
            colorBarView.backgroundColor = [UIColor colorFromHexCode:self.model.color];
            colorBarView.frame = CGRectMake(kWindowW - CELL_EDIT_RIGHT_MARGIN - imageWidth - 100 - CELL_EDIT_RIGHT_MARGIN, 25.0, 100, imageHeight);
            [self addSubview:colorBarView];
        }
        
    }
    
    [self addSubview:self.checkImageView];
    
    self.frame = CGRectMake(0, primaryY, kWindowW, localPrimarY);
    
    self.clickButton.frame = CGRectMake(0, 10, kWindowW, localPrimarY - 10);
    
    [self addSubview:self.clickButton];
    
    [superView addSubview:self];
    
    return primaryY + localPrimarY;
}

-(void)clickHandler{
    
    self.model.isSelected = !self.model.isSelected;
    
    if (self.model.subItems && self.model.subItems.count > 0) {
        
        for (int i = 0; i < self.model.subItems.count; i++) {
            
            CSSelectableModel *selectableModel = [self.model.subItems objectAtIndex:i];
            
            selectableModel.isSelected = self.model.isSelected;
        }
    }
}

#define KVO_KEY_IS_SELECTED @"isSelected"

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:KVO_KEY_IS_SELECTED]) {//安装功能项修改
        {
            [self changeSelectImage:self.model.isSelected];
        }
    }
    
}

-(void)setModel:(CSSelectableModel *)model{
    
    if(self.model != nil){
        [self.model removeObserver:self forKeyPath:KVO_KEY_IS_SELECTED];
    }
    
    _model = model;
    
    //设置按钮选中状态
    [self changeSelectImage:_model.isSelected];
    
    //KVO观察
    [self.model addObserver:self forKeyPath:KVO_KEY_IS_SELECTED options:NSKeyValueObservingOptionNew context:nil];
    
}

-(void)dealloc{
    
    //移除KVO观察
    [self.model removeObserver:self forKeyPath:KVO_KEY_IS_SELECTED];
    
}

-(UIImageView *)checkImageView{
    if (_checkImageView == nil) {
        _checkImageView = [[UIImageView alloc]init];
    }
    return _checkImageView;
}


-(void)changeSelectImage:(Boolean) isSelected{
    
    //设置按钮选中状态
    if (isSelected) {
        [self.checkImageView setImage:[CSPageEngine getImageWithKey:KEY_ICON_CHECKED]];
        
        if(self.selectedColor != nil){
            self.backgroundColor = self.selectedColor;
        }else{
            self.backgroundColor = COLOR_CONTROLER_SELECTED_MAIN;
        }
    }else{
        [self.checkImageView setImage:[CSPageEngine getImageWithKey:KEY_ICON_UNCHECKED]];
        self.backgroundColor = COLOR_CONTROLER_UNSELECTED_MAIN;
    }
    
}

-(CS_Page_TextView *)content_CS_Page_TextView{
    if (_content_CS_Page_TextView == nil) {
        _content_CS_Page_TextView = [CS_Page_TextView page_textViewWithFont:self.font textColor:self.textColor content:self.model.content textAlignment:NSTextAlignmentLeft];
        _content_CS_Page_TextView.leftMargin = self.leftMargin;
    }
    return _content_CS_Page_TextView;
}

-(UIButton *)clickButton{
    if (_clickButton == nil) {
        _clickButton = [[UIButton alloc] init];
        [_clickButton addTarget:self action:@selector(clickHandler) forControlEvents:UIControlEventTouchUpInside];
    }
    return _clickButton;
}

-(CS_Page_SectionTitleView *)content_CS_Page_SectionTitleView{
    if (_content_CS_Page_SectionTitleView == nil) {
        _content_CS_Page_SectionTitleView = [CS_Page_SectionTitleView page_SectionTitleView:self.model.content color:self.textColor image:nil];
        _content_CS_Page_SectionTitleView.backgroundColor = [UIColor redColor];
        if (self.font) {
            _content_CS_Page_SectionTitleView.font = self.font;
        }
    }
    return _content_CS_Page_SectionTitleView;
}

@end

@interface CS_Page_MultitpleSelectView()

@property (nonatomic, strong) NSArray *selectItems;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) UILabel *topLabel;
@property (nonatomic, copy) MultitpleSelectedBlock savedHandler;
@property (nonatomic,retain ) UIButton    *backButton;
@property (nonatomic,retain ) UIImageView *backButtonImageView;
@property (nonatomic, strong) UIButton *saveButton;

@end

@implementation CS_Page_MultitpleSelectView

+(id)page_MultitpleSelectView:(NSString *)title selectItems:(NSArray *)selectItems savedHandler:(MultitpleSelectedBlock)savedHandler{
    
    CS_Page_MultitpleSelectView *page_MultitpleSelectView = [CS_Page_MultitpleSelectView new];
    page_MultitpleSelectView.selectItems = selectItems;
    page_MultitpleSelectView.title = title;
    page_MultitpleSelectView.savedHandler = savedHandler;
    [page_MultitpleSelectView initView];
    
    return page_MultitpleSelectView;
}

/**
 * 查询栏风格的多选框
 * 其中selectItems中智能是selectableModel类型
 */
+(id)page_multitpleSelectViewWithSelectItems:(NSArray *)selectItems{
    
    CS_Page_MultitpleSelectView *page_MultitpleSelectView = [CS_Page_MultitpleSelectView new];
    page_MultitpleSelectView.selectItems = selectItems;
    page_MultitpleSelectView.multitpleSelectStyle = CS_MultitpleSelectStyle_QueryPanel;
    return page_MultitpleSelectView;
    
}

-(CGFloat)layoutView:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    if (self.multitpleSelectStyle == CS_MultitpleSelectStyle_QueryPanel) {
        
        CGFloat primaryX = 0;
        CGFloat localPrimaryY = 10.0;
        
        for (int i = 0; i < self.selectItems.count; i++) {
            
            CSSelectableModel *selectableModel = [self.selectItems objectAtIndex:i];
            
            NSString *buttonTitle = @"";
            
            buttonTitle = selectableModel.content;
            
            UIButton *conditionButton = [self getConditionButton:buttonTitle isSelected:selectableModel.isSelected];
            conditionButton.tag = i;
            
            if (conditionButton.frame.size.width + primaryX + MARGIN > kWindowW - 2 *CELL_EDIT_RIGHT_MARGIN) {
                
                localPrimaryY += HEIGHT_CONDITION_BUTTON + MARGIN;
                primaryX = 0;
                
            }
            
            conditionButton.frame = CGRectMake(primaryX + CELL_EDIT_RIGHT_MARGIN, localPrimaryY, conditionButton.frame.size.width, conditionButton.frame.size.height);
            [self addSubview:conditionButton];
            primaryX += conditionButton.frame.size.width + MARGIN;
            
        }
        
        //如果可选项大于0个
        localPrimaryY += HEIGHT_CONDITION_BUTTON + MARGIN;
        
        self.frame = CGRectMake(0, primaryY, kWindowW, localPrimaryY);
        
        [superView addSubview:self];
        
        return primaryY + localPrimaryY;
    }
    
    return primaryY;
    
}

-(UIButton *)getConditionButton:(NSString *)conditionButton isSelected:(BOOL)isSelected{
    
    UIButton *button = [UIButton new];
    [button setTitle:conditionButton forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:14.0];
    button.titleLabel.textColor = COLOR_TEXT_1;
    button.layer.borderColor = COLOR_TOP_SEPERATOR_LINE.CGColor;
    button.layer.borderWidth = 1.0;
    [button setTitleColor:COLOR_TEXT_0 forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 0, HEIGHT_CONDITION_BUTTON);
    [button sizeToFit];
    
    button.frame = CGRectMake(0, 0, button.frame.size.width + 20, HEIGHT_CONDITION_BUTTON);
    [button addTarget:self action:@selector(conditionSelectClick:) forControlEvents:UIControlEventTouchUpInside];
    
    if(isSelected == YES) {
        
        [self styleSelected:button];
        
    }else{
        
        [self styleUnSelected:button];
        
    }
    
    return button;
}

-(void)conditionSelectClick:(id)sender{
    
    UIButton *button = (UIButton *)sender;
    NSInteger index = button.tag;
    CSSelectableModel *selectableModel = (CSSelectableModel *)[self.selectItems objectAtIndex:index];
    if (selectableModel.isSelected) {
        
        [self styleUnSelected:button];
        selectableModel.isSelected = NO;
        
    }else{
        
        [self styleSelected:button];
        selectableModel.isSelected = YES;
        
    }
    
}

-(void)styleUnSelected:(UIButton *)button{
    [button setTitleColor:COLOR_TEXT_1 forState:UIControlStateNormal];
    button.layer.borderColor = COLOR_TOP_SEPERATOR_LINE.CGColor;
    button.layer.borderWidth = 1.0;
    
    UIImageView *imageView = (UIImageView *)[button viewWithTag:123];
    if (imageView) {
        [imageView removeFromSuperview];
    }
}

-(void)styleSelected:(UIButton *)button{
    UIColor *color_Selected = COLOR_THEME;
    [button setTitleColor:color_Selected forState:UIControlStateNormal];
    button.layer.borderColor = color_Selected.CGColor;
    button.layer.borderWidth = 1.0;
    
    UIImageView *imageView = (UIImageView *)[button viewWithTag:123];
    
    if (imageView == nil) {
        UIImage *image = [self scaleToSize:[CSPageEngine getImageWithKey:KEY_ICON_CHECK] size:CGSizeMake(11, 11)];
        imageView = [[UIImageView alloc] initWithImage:image];
        imageView.frame = CGRectMake(button.frame.size.width - 11, 0, 11, 11);
        imageView.tag = 123;
        [button addSubview:imageView];
    }
}

-(void)initView{
    
    //设置阴影
    self.frame = CGRectMake(0, 0, kWindowW, HEIGHT_CONTENT);

    self.backgroundColor = [UIColor whiteColor];
    
    UIScrollView *scrollView = [UIScrollView new];
    scrollView.frame = CGRectMake(0, 0, kWindowW, HEIGHT_CONTENT);
    [self addSubview:scrollView];
    
    CGFloat localPrimaryY = 0.0;
    
    for (int i = 0; i < self.selectItems.count; i++) {
        
        id selectableItem = [self.selectItems objectAtIndex:i];
        
        //如果是select model形式
        if ([selectableItem isKindOfClass:[CSSelectableModel class]]) {
            
            CSSelectableModel *selectableModel = (CSSelectableModel *)selectableItem;
            
            if (self.isSingleLevel) {//只有一个层级
                
                CSMainSelectView *mainSelectView = [CSMainSelectView mainSelectView:selectableModel textFont:[UIFont systemFontOfSize:FONT_SIZE_1] textColor:COLOR_TEXT_1 selectedColor:nil];
                
                localPrimaryY = [mainSelectView layoutView:scrollView primaryY:localPrimaryY];
                
            }else{//两个层级
                
                CSMainSelectView *mainSelectView = [CSMainSelectView mainSelectView:selectableModel textFont:[UIFont boldSystemFontOfSize:FONT_SIZE_1] textColor:COLOR_TEXT_2 selectedColor:nil];
                
                mainSelectView.isParentLevel = YES;
                
                localPrimaryY = [mainSelectView layoutView:scrollView primaryY:localPrimaryY];
                
                localPrimaryY = [self layoutSubview:scrollView primaryY:localPrimaryY parentModel:selectableModel leftMargin:mainSelectView.leftMargin];
                
            }
            
        }
    }
    
    scrollView.contentSize = CGSizeMake(0, localPrimaryY);
    
}

/**
 * 布局初始位置
 */
-(CGFloat)layoutSubview:(UIView *)superView primaryY:(CGFloat)primaryY parentModel:(CSSelectableModel *)parentModel leftMargin:(CGFloat)leftMargin{
    
    CGFloat localPrimaryY = primaryY;
    
    if (parentModel.subItems && parentModel.subItems.count > 0) {
        
        localPrimaryY += 10.0;
        
        for (int i = 0; i < parentModel.subItems.count; i++) {
            
            CSSelectableModel *subSelectModel = (CSSelectableModel *)[parentModel.subItems objectAtIndex:i];
            
            CSMainSelectView *mainSelectView = [CSMainSelectView mainSelectView:subSelectModel textFont:[UIFont systemFontOfSize:FONT_SIZE_1] textColor:COLOR_TEXT_2 selectedColor:[UIColor whiteColor]];
            
            mainSelectView.leftMargin = leftMargin + 20;
            
            localPrimaryY = [mainSelectView layoutView:superView primaryY:localPrimaryY];
            
            localPrimaryY = [self layoutSubview:superView primaryY:localPrimaryY parentModel:subSelectModel leftMargin:mainSelectView.leftMargin];
            
        }
        
        localPrimaryY += 10.0;
        
    }
    
    return localPrimaryY;
    
}

-(void)onRightBarButtonClick{
    
    NSString *selectedNamesString = @"";
    NSString *selectedCodesString = @"";
    
    for (int i = 0; i < self.selectItems.count; i++) {
        
        CSSelectableModel *selectableModel = [self.selectItems objectAtIndex:i];
        
        if (selectableModel.isSelected) {
            
            if ([self isNullOrEmpty:selectedNamesString]) {
                selectedNamesString = selectableModel.content;
                selectedCodesString = selectableModel.code;
            }else{
                selectedNamesString = [NSString stringWithFormat:@"%@, %@", selectedNamesString, selectableModel.content];
                selectedCodesString = [NSString stringWithFormat:@"%@, %@", selectedCodesString, selectableModel.code];
            }
            
        }
        
        for (int j = 0; j < selectableModel.subItems.count; j++) {
            
            CSSelectableModel *subSelectableModel = [selectableModel.subItems objectAtIndex:j];
            
            if (subSelectableModel.isSelected) {
                
                if ([self isNullOrEmpty:selectedNamesString]) {
                    selectedNamesString = subSelectableModel.content;
                    selectedCodesString = subSelectableModel.code;
                }else{
                    selectedNamesString = [NSString stringWithFormat:@"%@, %@", selectedNamesString, subSelectableModel.content];
                    selectedCodesString = [NSString stringWithFormat:@"%@, %@", selectedCodesString, subSelectableModel.code];
                }
                
            }
            
        }
    }
    
    if (self.savedHandler) {
        self.savedHandler(selectedNamesString, selectedCodesString);
    }
    
}

/**
 * 刷新数据
 */
-(void)refreshData{
    
    _selectCodes = @"";
    _selectNames = @"";
    
    for (int i = 0; i < self.selectItems.count; i++) {
        
        CSSelectableModel *selectableModel = [self.selectItems objectAtIndex:i];
        
        if (selectableModel.isSelected) {
            
            if ([self isNullOrEmpty:_selectNames]) {
                _selectNames = selectableModel.content;
                _selectCodes = selectableModel.code;
            }else{
                _selectNames = [NSString stringWithFormat:@"%@, %@", _selectNames, selectableModel.content];
                _selectCodes = [NSString stringWithFormat:@"%@, %@", _selectCodes, selectableModel.code];
            }
            
        }
        
        for (int j = 0; j < selectableModel.subItems.count; j++) {
            
            CSSelectableModel *subSelectableModel = [selectableModel.subItems objectAtIndex:j];
            
            if (subSelectableModel.isSelected) {
                
                if ([self isNullOrEmpty:_selectNames]) {
                    _selectNames = subSelectableModel.content;
                    _selectCodes = subSelectableModel.code;
                }else{
                    _selectNames = [NSString stringWithFormat:@"%@, %@", _selectNames, subSelectableModel.content];
                    _selectCodes = [NSString stringWithFormat:@"%@, %@", _selectCodes, subSelectableModel.code];
                }
            }
        }
    }
}

-(NSString *)selectNames{
    
    return _selectNames;
    
}

-(NSString *)selectCodes{
    
    return _selectCodes;
    
}

@end
